package com.coffee.test.copy;

import lombok.Data;
import org.apache.commons.lang3.SerializationUtils;
import org.springframework.beans.BeanUtils;

import java.io.Serializable;

@Data
public class User implements Serializable,Cloneable{
    private String username;
    private String password;
    private Address address;

    public User(String username, String password, Address address) {
        this.username = username;
        this.password = password;
        this.address = address;
    }

    public User() {
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        User user = (User) super.clone();
        user.address = (Address) address.clone();
        return user;
    }

    public static void main(String[] args) throws CloneNotSupportedException {
        Address address = new Address("zhejiang","hangzhou","liangzhu");

        User user = new User("admin","123456",address);

        User newUser = new User();
        //浅拷贝 拷贝出来的newUser中的address对象和原来的user中的address对象是同一个对象
        BeanUtils.copyProperties(user,newUser);
        user.getAddress().setCity("beijing");
        System.out.println(user.getAddress()==newUser.getAddress());
        System.out.println(user.getAddress());
        System.out.println(newUser.getAddress());

        //如何保证使得拷贝出来的newUser中的address对象和原来的user中的address对象是两个不同的对象 ==> 深拷贝
        //两种方式: 1、实现Cloneable接口,重写clone()  2、序列化实现深拷贝

        //实现Cloneable接口,重写clone()实现深拷贝
        User newUser2 = (User) user.clone();
        user.getAddress().setCity("shanghai");
        System.out.println(newUser2.getAddress()==user.getAddress());
        System.out.println(user.getAddress());
        System.out.println(newUser2.getAddress());

        //使用Apache Commons Lang中提供的SerializationUtils工具实现深拷贝
        User newUser3 = SerializationUtils.clone(user);
        user.getAddress().setCity("jiangxi");
        System.out.println(newUser3.getAddress()==user.getAddress());
        System.out.println(user.getAddress());
        System.out.println(newUser3.getAddress());

    }
}

